package android.pot.com.smartcar.util;

import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.pot.com.smartcar.R;
import android.pot.com.smartcar.ui.StartupPageActivity;
import android.support.annotation.RequiresApi;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by zhaoshilu on 2017/9/7.
 */

public class UpdateManagers{


    private static final String YOUR_CHANNEL_ID = "shifuhui_1001";

    private static final String YOUR_CHANNEL_NAME = "shifuhui";
    /* 下载中 */
    private static final int DOWNLOAD = 1;
    /* 下载结束 */
    private static final int DOWNLOAD_FINISH = 2;
    //判断是否更新中
    public static String tag = "1";//未点击更新

    /* 下载保存路径 */
    private String mSavePath;
    /* 记录进度条数量 */
    private int progress;
    /* 是否取消更新 */
    private boolean cancelUpdate = false;

    private String ver;//版本号
    private String urlapk;//apk地址
    private String notes;//升级说明
    private boolean isforce;
    private Context mContext;
    private int len;
    private NotificationManager manager;
    private Notification notif;
    /* 更新进度条 */
    private Dialog mDownloadDialog;
    //    RemoteViews contentView;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 正在下载
                case DOWNLOAD:
                    // 设置进度条位置
                    notif.contentView.setTextViewText(R.id.content_view_text1, "正在下载(" + progress + "%)");
                    notif.contentView.setProgressBar(R.id.content_view_progress, 100, progress, false);
                    manager.notify(0, notif);
                    break;
                case DOWNLOAD_FINISH:
                    // 安装文件
                    notif.contentView.setTextViewText(R.id.content_view_text1, "下载完成！");
                    notif.contentView.setProgressBar(R.id.content_view_progress, 100, 100, false);
                    manager.notify(0, notif);
                    tag = "2";//更新完成开始安装

                    checkVersion();

                    break;
                default:
                    break;
            }
        }

        ;
    };

    public UpdateManagers(Context context, String url, String msg,boolean isforce) {
        this.mContext = context;
        this.urlapk = url;
        this.notes = msg;
        this.isforce = isforce;
    }


    private OnInstallListener listener;

    public interface OnInstallListener {
        void install();
    }

    public void setInstallListener(OnInstallListener listener) {
        this.listener = listener;
    }


    /**
     * 检测软件更新
     */
    public void checkUpdate() {

        // 显示提示对话框
        if (tag.equals("1")) {
            showNoticeDialog();
        }

    }


    /**
     * 显示软件更新对话框
     */
    private void showNoticeDialog() {

        android.pot.com.smartcar.widget.AlertDialog dialog = new android.pot.com.smartcar.widget.AlertDialog(mContext)
                .builder()
                .setCancelable(false)
                .setTitle("智慧养车提示您")
                .setMsg(notes)
                .setPositiveButton("立即更新", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        Toast.makeText(mContext, "后台更新中,请稍后...", Toast.LENGTH_LONG).show();
                        tag = "3";//开始更新
                        showDownloadDialog();
                    }
                });
                if (!isforce){
                    dialog.setNegativeButton("暂不更新", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    });
                }
               dialog.show();
    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    public void CreateNotificationChannel(NotificationManager notificationManager) {
        NotificationChannel channel = new NotificationChannel(YOUR_CHANNEL_ID, YOUR_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
        notificationManager.createNotificationChannel(channel);
    }


    public void showDownloadDialog(){

        if (Build.VERSION.SDK_INT >= 26) {
            manager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
            CreateNotificationChannel(manager);
            notif = new Notification.Builder(mContext, YOUR_CHANNEL_ID).build();
            notif.icon = R.mipmap.logo;
            notif.tickerText = "更新通知";
            //通知栏显示所用到的布局文件
            notif.contentView = new RemoteViews(mContext.getPackageName(), R.layout.z_pp);
            manager.notify(0, notif);

        } else{
            //点击通知栏后打开的activity
            Intent intent = new Intent(mContext, StartupPageActivity.class);
            PendingIntent pIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
            manager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
            notif = new Notification();
            notif.icon = R.mipmap.logo;
            notif.tickerText = "更新通知";
            //通知栏显示所用到的布局文件
            notif.contentView = new RemoteViews(mContext.getPackageName(), R.layout.z_pp);
//        notif.contentIntent = pIntent;
            manager.notify(0, notif);
        }
        downloadApk();
    }
        /**
         * 下载apk文件
         */
    private void downloadApk() {
        // 启动新线程下载软件

        new downloadApkThread().start();
    }

    int downloadCount = 0;

    /**
     * 下载文件线程
     *
     * @author coolszy
     * @date 2012-4-26
     * @blog http://blog.92coding.com
     */
    private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {

                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    // 获得存储卡的路径
                    String sdpath = Environment.getExternalStorageDirectory() + "/";
                    mSavePath = sdpath + "download";
                    URL url = new URL(urlapk);
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    // 获取文件大小
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();

                    File file = new File(mSavePath);
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    File apkFile = new File(mSavePath, "shifuhui.apk");
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中


                    do {
                        int numread = is.read(buf);
                        count += numread;

                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 100);
                        Log.i("progress", "progress===" + progress);
                        Log.i("progress", "count===" + count + numread);
                        // 更新进度
                        //为了防止频繁的通知导致应用吃紧，百分比增加10才通知一次
                        if (downloadCount == 0 || progress - 5 > downloadCount) {
                            downloadCount += 5;
                            mHandler.sendEmptyMessage(DOWNLOAD);
                        }
                        if (numread <= 0) {
                            // 下载完成
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);
                    } while (!cancelUpdate);// 点击取消就停止下载.
                    fos.close();
                    is.close();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 检查版本
     */
    private void checkVersion() {
        installApk();
    }

    /**
     * 安装APK文件
     */
    public void installApk(){

        File apkfile = new File(mSavePath, "shifuhui.apk");
        if (!apkfile.exists()) {
            return;
        }
        // 通过Intent安装APK文件
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //判读版本是否在7.0以上
            Uri apkUri = FileProvider.getUriForFile(mContext, "android.pot.com.shifuhui.fileprovider", apkfile);//在AndroidManifest中的android:authorities值
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
//            // 更新后有引导图
            StartupUtils.clearFirstStartUp(mContext);
            mContext.startActivity(install);
        } else{
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
//            // 更新后有引导图
            StartupUtils.clearFirstStartUp(mContext);
            mContext.startActivity(intent);
        }
    }
}
